<template>
  <el-upload
    action="#"
    :http-request="(data) => { upload(data) }"
    accept=".sb3"
    :show-file-list="false"
    :disabled="form.id !== null || isUpload || !form.name || !form.pageURL"
  >
    <el-button :disabled="form.id !== null || isUpload || !form.name || !form.pageURL" plain>上传文件</el-button>
    <el-tag v-if="isUpload" type="success" style="margin-left: 10px">
      项目文件已上传
    </el-tag>
    <el-tag v-if="!isUpload && (!form.name || !form.pageURL)" type="warning" style="margin-left: 10px">
      请先填写名称并上传封面
    </el-tag>

  </el-upload>
</template>

<script>
import { putObejct } from '../../../utils/oss'
import { uploadFile } from '../../../api/file'
export default {
  name: 'FileUpload',
  props: {
    form: {
      type: Object,
      default: function() {
        return {
          id: null,
          name: '',
          pageURL: '',
          fileURL: '',
          type: ''
        }
      }
    }
    // page: {
    //   type: String,
    //   default: ''
    // },
    // file: {
    //   type: String,
    //   default: ''
    // },
    // id: {
    //   type: Number,
    //   default: null
    // }
  },
  data() {
    return {
      isUpload: false
    }
  },
  methods: {
    /**
     * 项目文件上传
     * @param {Object} data
     * */
    upload(data) {
      const that = this
      if (this.beforeUpload(data.file)) {
        putObejct(data.file, 'works', function(res) {
          console.log(res.Location)
          const config = {
            name: that.form.name,
            fileURL: 'http://' + res.Location,
            pageURL: that.form.pageURL,
            type: 'sb3'
          }
          uploadFile(config)
            .then(response => {
              that.isUpload = true
              // 1秒后刷新
              config['id'] = response.data.work_id
              config['updatedAt'] = Date.now()
              setTimeout(function() {
                // that.$emit('reload')
                that.$emit('create', config)
              }, 1000)
            }).catch(err => {
              console.log(err)
            })
        })
      }
    },
    /**
     * 获得文件的后缀名
     * @param {Object} file
     * @return {string | boolean}
     * */
    getFileType(file) {
      if (file.name && file.name.lastIndexOf('.') > 0) {
        return file.name.substring(file.name.lastIndexOf('.') + 1, file.length)
      }
      return false
    },
    /**
     * 上传前校验格式与大小
     * @param {Object} file
     * @return {boolean}
     * */
    beforeUpload(file) {
      const isSb3 = this.getFileType(file) === 'sb3'
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isSb3) {
        this.$message.error('文件只能是 SB3 格式!')
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 10MB!')
      }
      return isSb3 && isLt10M
    }
  }
}
</script>

<style scoped>

</style>
